package com.zxt.content.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;
import com.zxt.utils.StringUtils;

import java.util.regex.Pattern;

@Component
public class PasswordEncoderUtil {
    private static final Logger log = LoggerFactory.getLogger(PasswordEncoderUtil.class);
    private Pattern BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");

    public PasswordEncoderUtil() {
    }

    public String encode(CharSequence rawPassword) {
        if (StringUtils.isNotEmpty(rawPassword)) {
            String salt = BCrypt.gensalt();
            return BCrypt.hashpw(rawPassword.toString(), salt);
        } else {
            return null;
        }
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword != null && encodedPassword.length() != 0) {
            if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
                log.warn("Encoded password does not look like BCrypt");
                return false;
            } else {
                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
            }
        } else {
            log.warn("Empty encoded password");
            return false;
        }
    }
}
